/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.factory.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.FactorySampleException;
import com.pitop.factory.dao.FactorySampleDAO;
import com.pitop.factory.entity.FactorySample;
import com.pitop.factory.entity.FactorySampleState;
import com.pitop.sync.entity.SyncNewData;
import com.pitop.sync.entity.SyncNewDataEventState;
import com.pitop.sync.entity.SyncNewDataState;
import com.pitop.sync.entity.SyncTraceModel;
import com.pitop.sync.service.SyncNewDataSV;
import com.pitop.test.dao.TestOptionDAO;
import com.pitop.test.entity.TestOption;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("factorySampleSV")
@Slf4j
public class FactorySampleSVImpl extends BaseSVImpl<FactorySample, Long> implements FactorySampleSV {

    @Autowired
    private FactorySampleDAO factorySampleDAO;

    @Autowired
    private SyncNewDataSV syncNewDataSV;

    @Autowired
    private TestOptionDAO testOptionDAO;

    @Override
    protected BaseDAO getBaseDAO() {
        return factorySampleDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     */
    @Override
    public void save(FactorySample entity) throws BaseException {
        entity.setState(FactorySampleState.Enable.name());
        entity.setVer(1);
        super.save(entity);

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("sampleCode", entity.getSampleCode());
        paraMap.put("factoryCode", entity.getFactoryCode());
        FactorySample factorySample = factorySampleDAO.load(paraMap);
        if (factorySample != null) {
            //同时更新到需要同步的数据表
            syncNewDataSV.save(factorySample.getFactoryCode(), SyncTraceModel.Sample.name(), SyncNewDataEventState.Insert.name(), factorySample.getSampleCode(), 1, SyncNewDataState.Ready.name());
        }

        List<TestOption> testOptions = testOptionDAO.loadBySampleCode(entity.getSampleCode());
        if (testOptions != null && !testOptions.isEmpty()) {
            for (TestOption testOption : testOptions) {
                List<SyncNewData> syncNewDataList = syncNewDataSV.listByDataCode(testOption.getCode());
                if (syncNewDataList == null || syncNewDataList.isEmpty()) {
                    //同时更新到需要同步的数据表
                    syncNewDataSV.save(entity.getFactoryCode(), SyncTraceModel.Test_option.name(), SyncNewDataEventState.Insert.name(), testOption.getCode(), 1, SyncNewDataState.Ready.name());
                }
            }
        }


    }


    /**
     * 数据更新
     *
     * @param factorySample 工厂样品实体
     */
    @Override
    public void modify(FactorySample factorySample) throws BaseException {
        int oldVer = load(null, factorySample.getSampleCode(), factorySample.getFactoryCode()).getVer();
        factorySample.setVer(oldVer + 1);
        Map<String, Object> paraMap = JSON.parseObject(JSON.toJSONString(factorySample, SerializerFeature.WriteDateUseDateFormat));
        paraMap.put("oldVer", oldVer);
        getBaseDAO().update(paraMap);

        if (FactorySampleState.getEnum(factorySample.getState()).equals(FactorySampleState.Enable)) {
            factorySample = load(null, factorySample.getSampleCode(), factorySample.getFactoryCode());
            if (factorySample != null) {
                //同时更新到需要同步的数据表
                syncNewDataSV.save(factorySample.getFactoryCode(), SyncTraceModel.Sample.name(), SyncNewDataEventState.Update.name(), factorySample.getSampleCode(), 1, SyncNewDataState.Ready.name());
            }

            List<TestOption> testOptions = testOptionDAO.loadBySampleCode(factorySample.getSampleCode());
            if (testOptions != null && !testOptions.isEmpty()) {
                for (TestOption testOption : testOptions) {
                    List<SyncNewData> syncNewDataList = syncNewDataSV.listByDataCode(testOption.getCode());
                    if (syncNewDataList == null || syncNewDataList.isEmpty()) {
                        //同时更新到需要同步的数据表
                        syncNewDataSV.save(factorySample.getFactoryCode(), SyncTraceModel.Test_option.name(), SyncNewDataEventState.Insert.name(), testOption.getCode(), 1, SyncNewDataState.Ready.name());
                    } else {
                        //同时更新到需要同步的数据表
                        syncNewDataSV.save(factorySample.getFactoryCode(), SyncTraceModel.Test_option.name(), SyncNewDataEventState.Update.name(), testOption.getCode(), 1, SyncNewDataState.Ready.name());
                    }
                }
            }

        }

    }


    /**
     * 加载一个对象FactorySample
     *
     * @param id id* @param sampleCode 样品编码* @param factoryCode 工厂编码
     * @return FactorySample
     */
    @Override
    public FactorySample load(java.lang.Long id, java.lang.String sampleCode, java.lang.String factoryCode) {
        if (id == null && sampleCode == null && factoryCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("sampleCode", sampleCode);
        param.put("factoryCode", factoryCode);
        return factorySampleDAO.load(param);
    }

    /**
     * 加载一个对象FactorySample 通过id
     *
     * @param id id
     * @return FactorySample
     */
    @Override
    public FactorySample loadById(java.lang.Long id) {
        if (id == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return factorySampleDAO.loadById(id);
    }

    /**
     * 加载一个对象FactorySample 通过sampleCode
     *
     * @param sampleCode 样品编码
     * @return List<FactorySample>
     */
    @Override
    public List<FactorySample> listBySampleCode(java.lang.String sampleCode) {
        if (sampleCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return factorySampleDAO.listBySampleCode(sampleCode);
    }

    /**
     * 加载一个对象FactorySample 通过factoryCode
     *
     * @param factoryCode 工厂编码
     * @return List<FactorySample>
     */
    @Override
    public List<FactorySample> listByFactoryCode(java.lang.String factoryCode) {
        if (factoryCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return factorySampleDAO.listByFactoryCode(factoryCode);
    }


    /**
     * 根据主键id,oldStates 共同更新 FactorySample 的状态到newState状态
     *
     * @param id        id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(java.lang.Long id, FactorySampleState newState, FactorySampleState... oldStates) {
        if (id == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        factorySampleDAO.updateStateById(id, newState, oldStates);
    }

    /**
     * 根据主键sampleCode,oldStates 共同更新 FactorySample 的状态到newState状态
     *
     * @param sampleCode 样品编码
     * @param newState   新状态
     * @param oldStates  旧状态集合
     */
    @Override
    public void updateStateBySampleCode(java.lang.String sampleCode, FactorySampleState newState, FactorySampleState... oldStates) {
        if (sampleCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        factorySampleDAO.updateStateBySampleCode(sampleCode, newState, oldStates);
    }

    /**
     * 根据主键factoryCode,oldStates 共同更新 FactorySample 的状态到newState状态
     *
     * @param factoryCode 工厂编码
     * @param newState    新状态
     * @param oldStates   旧状态集合
     */
    @Override
    public void updateStateByFactoryCode(java.lang.String factoryCode, FactorySampleState newState, FactorySampleState... oldStates) {
        if (factoryCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        factorySampleDAO.updateStateByFactoryCode(factoryCode, newState, oldStates);
    }

    /**
     * 根据主键id 更新 FactorySample 的状态到另一个状态
     *
     * @param id    id
     * @param state 状态
     */
    @Override
    public void updateById(java.lang.Long id, FactorySampleState state) {
        if (id == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        factorySampleDAO.updateById(id, state);
    }

    /**
     * 根据主键sampleCode 更新 FactorySample 的状态到另一个状态
     *
     * @param sampleCode 样品编码
     * @param state      状态
     */
    @Override
    public void updateBySampleCode(java.lang.String sampleCode, FactorySampleState state) {
        if (sampleCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        factorySampleDAO.updateBySampleCode(sampleCode, state);
    }

    /**
     * 根据主键factoryCode 更新 FactorySample 的状态到另一个状态
     *
     * @param factoryCode 工厂编码
     * @param state       状态
     */
    @Override
    public void updateByFactoryCode(java.lang.String factoryCode, FactorySampleState state) {
        if (factoryCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        factorySampleDAO.updateByFactoryCode(factoryCode, state);
    }


    /**
     * 删除对象FactorySample
     *
     * @param id          id
     * @param sampleCode  样品编码
     * @param factoryCode 工厂编码
     */
    @Override
    public void delete(java.lang.Long id, java.lang.String sampleCode, java.lang.String factoryCode) {
        if (id == null && sampleCode == null && factoryCode == null) {
            throw new FactorySampleException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("sampleCode", sampleCode);
        param.put("factoryCode", factoryCode);

        List<FactorySample> factorySamples = new ArrayList<>();
        if (StringUtils.isNotBlank(sampleCode)) {
            factorySamples = factorySampleDAO.listBySampleCode(sampleCode);
        } else if (StringUtils.isNotBlank(factoryCode)) {
            factorySamples.clear();
            factorySamples = factorySampleDAO.listByFactoryCode(factoryCode);
        } else if (id != null) {
            factorySamples.clear();
            factorySamples.add(factorySampleDAO.loadById(id));
        }

        factorySampleDAO.delete(param);

        if (factorySamples != null && factorySamples.size() > 0) {
            for (FactorySample factorySample : factorySamples) {
                //同时更新到需要同步的数据表
                syncNewDataSV.save(factorySample.getFactoryCode(), SyncTraceModel.Sample.name(), SyncNewDataEventState.Delete.name(), factorySample.getSampleCode(), 1, SyncNewDataState.Ready.name());
            }
        }


    }


    /**
     * 查询FactorySample分页
     *
     * @param factorySample 对象
     * @param offset        查询开始行
     * @param limit         查询行数
     * @return List<FactorySample>
     */
    @Override
    public List<FactorySample> list(FactorySample factorySample, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = new HashMap<>();
        if (factorySample != null) {
            map = JSON.parseObject(JSON.toJSONString(factorySample, SerializerFeature.WriteDateUseDateFormat));
        }
        return factorySampleDAO.list(map, new RowBounds(offset, limit));
    }

    /**
     * 统计
     *
     * @param factorySample 工厂样品实体
     * @return int
     */
    @Override
    public int count(FactorySample factorySample) {
        Map<String, Object> map = new HashMap<>();
        if (factorySample != null) {
            map = JSON.parseObject(JSON.toJSONString(factorySample, SerializerFeature.WriteDateUseDateFormat));
        }
        return factorySampleDAO.count(map);
    }

    /**
     * 查询FactorySample分页
     *
     * @param id     id* @param sampleCode  样品编码* @param factoryCode  工厂编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<FactorySample>
     */
    @Override
    public List<FactorySample> list(java.lang.Long id, java.lang.String sampleCode, java.lang.String factoryCode, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("sampleCode", sampleCode);
        param.put("factoryCode", factoryCode);
        return factorySampleDAO.list(param, new RowBounds(offset, limit));
    }

    /**
     * 统计
     *
     * @param id          id
     * @param sampleCode  样品编码
     * @param factoryCode 工厂编码
     * @return int
     */
    @Override
    public int count(java.lang.Long id, java.lang.String sampleCode, java.lang.String factoryCode) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("sampleCode", sampleCode);
        param.put("factoryCode", factoryCode);
        return factorySampleDAO.count(param);
    }

}
